﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DvtCap;
using Newtonsoft.Json.Linq;

namespace HttpTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
        }

        JToken get(JObject jobj, string key, JToken _default)
        {
            if (jobj.ContainsKey(key))
            {
                return jobj[key];
            }
            else
            {
                return _default;
            }
        }

        string configfile = "history.config";
        void LoadConfig()
        {
            if (File.Exists(configfile))
            {
                string ctx = File.ReadAllText(configfile);
                JObject history = JObject.Parse(ctx);
                txt_server_ip.Text = get(history, "server_ip", "0.0.0.0").ToString();
                txt_server_port.Text = get(history, "server_port", "8080").ToString();

                txt_client_ip.Text = get(history, "client_ip", "192.168.1.238").ToString();
                txt_client_port.Text = get(history, "client_port", "8080").ToString();

                txt_http_host.Text = get(history, "http_host", "192.168.1.238").ToString();
                txt_http_port.Text = get(history, "http_port", "8080").ToString();
                txt_http_notifyUri.Text = get(history, "http_notifyUri", "/api/v1/camera/faceNotify").ToString();

                txt_devId.Text = get(history, "devId", "0000FFF3").ToString();
                txt_camId.Text = get(history, "camId", "0").ToString();
            }
        }

        void SaveConfig()
        {
            JObject history = new JObject();
            history["server_ip"] = txt_server_ip.Text;
            history["server_port"] = txt_server_port.Text;

            history["client_ip"] = txt_client_ip.Text;
            history["client_port"] = txt_client_port.Text;

            history["http_host"] = txt_http_host.Text;
            history["http_port"] = txt_http_port.Text;
            history["http_notifyUri"] = txt_http_notifyUri.Text;
            history["devId"] = txt_devId.Text;
            history["camId"] = txt_camId.Text;
            File.WriteAllText(configfile, history.ToString(Newtonsoft.Json.Formatting.Indented));
        }



        HttpWarpper httpServer;
        HttpClient httpClient;



        //private void OnVlcControlNeedsLibDirectory(object sender, Vlc.DotNet.Forms.VlcLibDirectoryNeededEventArgs e)
        //{
        //    var currentAssembly = Assembly.GetEntryAssembly();
        //    var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;
        //    if (currentDirectory == null)
        //        return;
        //    if (AssemblyName.GetAssemblyName(currentAssembly.Location).ProcessorArchitecture == ProcessorArchitecture.X86)
        //        e.VlcLibDirectory = new DirectoryInfo(Path.Combine(Application.StartupPath, @"libvlc\win-x86"));
        //    else
        //        e.VlcLibDirectory = new DirectoryInfo(Path.Combine(Application.StartupPath, @"libvlc\win-x64"));
        //}

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadConfig();
            tabControl1.SelectedIndex = 1;

            List<ComboBox> list = new List<ComboBox>{ cb_captureType , cb_stream_index ,cb_backgroupUpload,cb_fixedEnable,cb_http_enabled,cb_norepeatEnable,cb_roi_enabled};
            foreach (var item in list)
            {
                item.SelectedIndex = 0;
            }
            Bitmap bmp = new Bitmap(100, 100);
            Utils.ImageToBase64(bmp);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveConfig();
            httpServer?.Stop();
            Process.GetCurrentProcess().Kill();
        }

        FFmpegDemuxerWrapper demuxerWrapper;
        RendererWrapper renderer;
        H264DecoderWrapper h264Decoder;
        private unsafe void btn_start_servise_Click(object sender, EventArgs e)
        {
            httpServer = new HttpWarpper(txt_server_ip.Text, Convert.ToInt32(txt_server_port.Text));
            httpServer.onRequest += HttpServer_onRequest;
            bool ret = httpServer.Start();


            httpClient = new HttpClient(txt_client_ip.Text, Convert.ToInt32(txt_client_port.Text));
            //httpClient.Post("/mm", "");
            listBox1.Items.Insert(0, "start ok.");
            string mrl = string.Format("rtsp://{0}:554/onvif/live/1/{1}", txt_client_ip.Text, cb_stream_index.SelectedIndex + 1);
            //vlcControl1.Play(mrl);
            if (demuxerWrapper != null)
            {
                demuxerWrapper.onBufferGrab -= DemuxerWrapper_onBufferGrab;
            }
            if (renderer == null)
            {
                renderer = new RendererWrapper(pictureBox1.Handle);
                renderer.init(PixelFormatEnum.PIXELFORMAT_IYUV);
            }
            if (h264Decoder == null)
            {
                h264Decoder = new H264DecoderWrapper();
            }
            demuxerWrapper = new FFmpegDemuxerWrapper(mrl);
            demuxerWrapper.onBufferGrab += DemuxerWrapper_onBufferGrab;
            listBox1.Items.Insert(0, "play rtsp >>> " + mrl);
        }

        //FileStream fileStream = new FileStream("1.h264", FileMode.Create);
        private unsafe void DemuxerWrapper_onBufferGrab(void* buf, int len)
        {
            //byte[] data = new byte[len];
            //Marshal.Copy(new IntPtr(buf), data, 0, len);
            //fileStream.Write(data, 0, len);
            if (h264Decoder.decode(buf, len))
            {
                byte* p0, p1, p2;
                int Ystride, UVstride, stride2;
                h264Decoder.getPtrYUV(&p0, &p1, &p2);
                h264Decoder.getStride(&Ystride, &UVstride, &stride2);
                int w = h264Decoder.getWidth();
                int h = h264Decoder.getHeight();
                renderer.renderIYUV(p0, p1, p2, Ystride, UVstride, UVstride, w, h);
                renderer.Present();
            }
            //Thread.Sleep(10);
        }

        private string HttpServer_onRequest(string endpoint, string requestBody, HttpClient.RequestMethod requestMethod)
        {
            switch (endpoint)
            {
                case "/grg/camera/heartBeat":
                    BeginInvoke(new Action(() =>
                    {
                        listBox1.Items.Insert(0, "heartBeat >>> " + requestBody);
                    }));
                    break;
                case "/grg/camera/status":
                    BeginInvoke(new Action(() =>
                    {
                        listBox1.Items.Insert(0, "status >>> " + requestBody);
                    }));
                    break;
                case "/grg/camera/setHeartConfig":
                    BeginInvoke(new Action(() =>
                    {
                        listBox1.Items.Insert(0, "setHeartConfig >>> " + requestBody);
                    }));
                    break;
                case "/grg/camera/personStatus":
                    BeginInvoke(new Action(() =>
                    {
                        listBox1.Items.Insert(0, "personStatus >>> " + requestBody);
                    }));
                    break;
                case "/grg/camera/captureOncePicture":
                    BeginInvoke(new Action(() =>
                    {
                        listBox1.Items.Insert(0, "captureOncePicture >>> " + requestBody);
                    }));
                    break;
                case "/grg/camera/faceNotify":
                    BeginInvoke(new Action(() =>
                    {
                        listBox1.Items.Insert(0, "faceNotify >>> " + requestBody);
                    }));
                    break;
                case "/api/v1/camera/faceNotify":
                    BeginInvoke(new Action(() =>
                    {
                        listBox1.Items.Insert(0, "api_faceNotify >>> " + requestBody);
                    }));
                    break;
                case "/grg/camera/startup":
                    BeginInvoke(new Action(() =>
                    {
                        listBox1.Items.Insert(0, "startup >>> " + requestBody);
                    }));
                    break;
                case "/grg/camera/standby":
                    BeginInvoke(new Action(() =>
                    {
                        listBox1.Items.Insert(0, "standby >>> " + requestBody);
                    }));
                    break;
                default:
                    break;
            }
            return "{\"code\": 0,\"msg\": \"success\"}";
        }

        int index = 1;
        private void btn_select_image_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Bitmap bmp = new Bitmap(openFileDialog1.FileName);
                    tb_addperson_list.Rows.Add(new object[] { index, Utils.GetRandomStr(), Utils.GetRandomName(true, 1), Utils.GetRandomName(true, 2), Utils.GetRandomPhoneNumber(), DateTime.Now.ToString("yyyyMMddhhmmss"), bmp });
                    index++;
                }
                catch (Exception)
                {

                    MessageBox.Show("plz select an image ok?");
                }
            }
        }

        private void btn_addpersons_Click(object sender, EventArgs e)
        {
            JObject msg = new JObject();
            JArray persons = new JArray();
            for (int i = 0; i < tb_addperson_list.Rows.Count; i++)
            {
                JObject jObject = new JObject();
                jObject["index"] = tb_addperson_list.Rows[i].Cells[0].Value.ToString();
                jObject["personId"] = tb_addperson_list.Rows[i].Cells[1].Value.ToString();
                jObject["firstName"] = tb_addperson_list.Rows[i].Cells[2].Value.ToString();
                jObject["lastName"] = tb_addperson_list.Rows[i].Cells[3].Value.ToString();
                jObject["phone"] = tb_addperson_list.Rows[i].Cells[4].Value.ToString();
                jObject["updateTime"] = tb_addperson_list.Rows[i].Cells[5].Value.ToString();
                JArray images = new JArray();
                JObject image = new JObject();
                image["data"] = "data:image/jpeg;base64," + Utils.ImageToBase64((Bitmap)tb_addperson_list.Rows[i].Cells[6].Value);
                images.Add(image);
                jObject["images"] = images;
                persons.Add(jObject);
            }
            msg["persons"] = persons;
            string msg_str = msg.ToString();
            if (httpClient != null)
            {
                string response = httpClient.Post("/grg/camera/addPersons", msg_str);
                listBox1.Items.Insert(0, response);
            }
        }

        private void btn_delete_Click(object sender, EventArgs e)
        {
            if (tb_addperson_list.SelectedCells.Count > 0)
            {
                JObject msg = new JObject();
                msg["personId"] = tb_addperson_list.Rows[tb_addperson_list.SelectedCells[0].RowIndex].Cells[1].Value.ToString();
                string msg_str = msg.ToString();
                if (httpClient != null)
                {
                    string response = httpClient.Post("/grg/camera/deletePerson", msg_str);
                    JObject responseJ = JObject.Parse(response);
                    if (responseJ["code"].ToObject<int>() == 0)
                    {
                        tb_addperson_list.Rows.RemoveAt(tb_addperson_list.SelectedCells[0].RowIndex);
                    }
                    listBox1.Items.Insert(0, response);
                }

            }
        }

        private void btn_modify_Click(object sender, EventArgs e)
        {
            if (tb_addperson_list.SelectedCells.Count > 0)
            {
                JObject msg = new JObject();
                msg["personId"] = tb_addperson_list.Rows[tb_addperson_list.SelectedCells[0].RowIndex].Cells[1].Value.ToString();
                msg["firstName"] = tb_addperson_list.Rows[tb_addperson_list.SelectedCells[0].RowIndex].Cells[2].Value.ToString();
                msg["lastName"] = tb_addperson_list.Rows[tb_addperson_list.SelectedCells[0].RowIndex].Cells[3].Value.ToString();
                msg["phone"] = tb_addperson_list.Rows[tb_addperson_list.SelectedCells[0].RowIndex].Cells[4].Value.ToString();
                msg["updateTime"] = tb_addperson_list.Rows[tb_addperson_list.SelectedCells[0].RowIndex].Cells[5].Value.ToString();
                string msg_str = msg.ToString();
                if (httpClient != null)
                {
                    string response = httpClient.Post("/grg/camera/modifyPerson", msg_str);
                    listBox1.Items.Insert(0, response);
                }
            }
        }

        private void btn_query_Click(object sender, EventArgs e)
        {
            if (tb_addperson_list.SelectedCells.Count > 0)
            {
                JObject msg = new JObject();
                msg["personId"] = tb_addperson_list.Rows[tb_addperson_list.SelectedCells[0].RowIndex].Cells[1].Value.ToString();
                string msg_str = msg.ToString();
                if (httpClient != null)
                {
                    string response = httpClient.Post("/grg/camera/queryPerson", msg_str);
                    listBox1.Items.Insert(0, response);
                }
            }
        }

        private void btn_query_all_Click(object sender, EventArgs e)
        {
            JObject msg = new JObject();
            msg["pageIndex"] = 1;
            msg["pageSize"] = 20;
            string msg_str = msg.ToString();
            if (httpClient != null)
            {
                string response = httpClient.Post("/grg/camera/queryAllPerson", msg_str);
                listBox1.Items.Insert(0, response);
            }


        }

        private void btn_query_statistics_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                string response = httpClient.Post("/grg/camera/queryStatistics", "");
                listBox1.Items.Insert(0, response);
            }

        }

        private void btn_downloa_persions_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                string response = httpClient.Post("/grg/camera/downloadPersons", "");
                //"data": [ { "personId": "1YPUST806SB8G6UTXS4VQDM88OPU0OB6", "firstName": "荀", "lastName": "启", "phone": "15007641473", "faceId": 
                var objs = JObject.Parse(response)["data"];
                foreach (var item in objs)
                {
                    bool b_contain = false;
                    for (int i = 0; i < tb_addperson_list.Rows.Count; i++)
                    {
                        if (tb_addperson_list.Rows[i].Cells[1].Value.ToString() == item["personId"].ToString())
                        {
                            b_contain = true;
                            break;
                        }
                    }
                    if (!b_contain)
                    {
                        var line = new object[] { tb_addperson_list.Rows.Count, item["personId"], item["firstName"], item["lastName"], item["phone"], DateTime.Now.ToString("yyyyMMddhhmmss") };
                        tb_addperson_list.Rows.Add(line);
                    }
              
                }
                listBox1.Items.Insert(0, response);
            }
        }


        private void btn_reset_database_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject body = new JObject();
                body["devId"] = txt_devId.Text;
                string response = httpClient.Post("/grg/camera/resetPersons", body.ToString());
                listBox1.Items.Insert(0, response);
            }

        }

        private void btn_recog_local_image_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {

                    using (FileStream stream = File.OpenRead(openFileDialog1.FileName))
                    {
                        byte[] content = new byte[stream.Length];

                        for (int i = 0; i < content.Length; i++)
                        {
                            content[i] = (byte)stream.ReadByte();
                        }

                        string ctx = Convert.ToBase64String(content);

                        JObject image = new JObject();
                        image["data"] = "data:image/jpeg;base64," + ctx;
                        if (httpClient != null)
                        {
                            Stopwatch sw = new Stopwatch();
                            sw.Start();
                            string response = httpClient.Post("/grg/camera/faceRecognition", image.ToString());
                            sw.Stop();
                            listBox1.Items.Insert(0, "cost >>> " + sw.ElapsedMilliseconds + " ms");

                            listBox1.Items.Insert(0, response);
                        }
                    }

#if false
                    Bitmap bmp = new Bitmap(openFileDialog1.FileName);
                    JObject image = new JObject();
                    image["data"] = "data:image/jpeg;base64," + Utils.ImageToBase64(bmp);
                    if (httpClient != null)
                    {
                        string response = httpClient.Post("/grg/camera/faceRecognition", image.ToString());
                        listBox1.Items.Insert(0, response);
                    }
#endif
                }
                catch (Exception)
                {

                    MessageBox.Show("plz select an image ok?");
                }
            }
        }

        private void btn_remote_takepic_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject body = new JObject();
                body["devId"] = txt_devId.Text;
                string response = httpClient.Post("/grg/camera/takePicture", body.ToString());
                int len = response.Length;
                listBox1.Items.Insert(0, response);
            }

        }

        private void btn_get_http_info_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject body = new JObject();
                body["devId"] = txt_devId.Text;
                string response = httpClient.Post("/grg/camera/getHttpConfig", body.ToString());
                listBox1.Items.Insert(0, response);

                JObject httpinfo = JObject.Parse(response);
                if (httpinfo["code"].ToObject<int>() == 0)
                {
                    cb_http_enabled.Text = httpinfo["data"]["enabled"].ToObject<string>();
                    txt_http_host.Text = httpinfo["data"]["serverHost"].ToObject<string>();
                    txt_http_port.Text = httpinfo["data"]["serverPort"].ToObject<int>().ToString();
                    txt_http_notifyUri.Text = httpinfo["data"]["notifyUri"].ToObject<string>();

                }

            }
        }

        private void btn_set_http_info_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject httpinfo = new JObject();
                httpinfo["devId"] = txt_devId.Text;
                httpinfo["enabled"] = cb_http_enabled.Text;
                httpinfo["serverHost"] = txt_http_host.Text;
                httpinfo["serverPort"] = Convert.ToInt32(txt_http_port.Text);
                httpinfo["notifyUri"] = txt_http_notifyUri.Text;
                string response = httpClient.Post("/grg/camera/setHttpConfig", httpinfo.ToString());
                listBox1.Items.Insert(0, response);
            }
        }

        private void btn_reboot_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject body = new JObject();
                body["devId"] = txt_devId.Text;
                string response = httpClient.Post("/grg/camera/reboot", body.ToString()); ;
                listBox1.Items.Insert(0, response);
            }
        }

        private void btn_work_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject body = new JObject();
                body["devId"] = txt_devId.Text;
                string response = httpClient.Post("/grg/camera/startWorkMode", body.ToString());
                listBox1.Items.Insert(0, "startWork　>>>　" +　response);
            }
        }

        private void btn_startup_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject httpinfo = new JObject();
                httpinfo["devId"] = txt_devId.Text;
                httpinfo["time"] = DateTime.Now.ToString("yyyyMMddhhmmss");
                string response = httpClient.Post("/grg/camera/startup", httpinfo.ToString());
                listBox1.Items.Insert(0, response);
            }
        }

        private void btn_reset_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject body = new JObject();
                body["devId"] = txt_devId.Text;
                string response = httpClient.Post("/grg/camera/reset", body.ToString());
                listBox1.Items.Insert(0, response);
            }
        }

        private void btn_standby_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject body = new JObject();
                body["devId"] = txt_devId.Text;
                string response = httpClient.Post("/grg/camera/standby", body.ToString());
                listBox1.Items.Insert(0, response);
            }
        }

        private void btn_getfaceconfig_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject body = new JObject();
                body["devId"] = txt_devId.Text;
                string response = httpClient.Post("/grg/camera/getFaceConfig", body.ToString());
                listBox1.Items.Insert(0, response);

                JObject faceconfig = JObject.Parse(response);
                if (faceconfig["code"].ToObject<int>() == 0)
                {
                    cb_captureType.Text = faceconfig["data"]["captureStandard"]["captureType"].ToObject<string>();
                    cb_backgroupUpload.Text = faceconfig["data"]["captureStandard"]["backgroupUpload"].ToObject<string>();
                    txt_height.Text = faceconfig["data"]["captureStandard"]["imageHeight"].ToObject<int>().ToString();
                    txt_imageQuality.Text = faceconfig["data"]["captureStandard"]["imageQuality"].ToObject<string>();
                    txt_width.Text = faceconfig["data"]["captureStandard"]["imageWidth"].ToObject<int>().ToString();

                    cb_fixedEnable.Text = faceconfig["data"]["captureStandard"]["targetStandard"]["fixedEnable"].ToObject<string>();
                    txt_fixedSize.Text = faceconfig["data"]["captureStandard"]["targetStandard"]["fixedSize"].ToObject<int>().ToString();
                    txt_imageType.Text = faceconfig["data"]["captureStandard"]["targetStandard"]["imageType"].ToObject<string>();
                    txt_underHeightRatio.Text = faceconfig["data"]["captureStandard"]["targetStandard"]["underHeightRatio"].ToObject<double>().ToString();
                    txt_widthRatio.Text = faceconfig["data"]["captureStandard"]["targetStandard"]["widthRatio"].ToObject<double>().ToString();
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject faceconfig = new JObject();
                faceconfig["captureStandard"] = new JObject();
                faceconfig["captureStandard"]["captureType"] = cb_captureType.Text;
                faceconfig["captureStandard"]["captureInterval"] = Convert.ToInt32(txt_captureInterval.Text);
                faceconfig["captureStandard"]["norepeatEnable"] = cb_norepeatEnable.Text;
                faceconfig["captureStandard"]["norepeatInterval"] = Convert.ToInt32(txt_norepeatInterval.Text);
                faceconfig["captureStandard"]["backgroupUpload"] = cb_backgroupUpload.Text;
                faceconfig["captureStandard"]["imageHeight"] = Convert.ToInt32(txt_height.Text);
                faceconfig["captureStandard"]["imageQuality"] = txt_imageQuality.Text;
                faceconfig["captureStandard"]["imageWidth"] = Convert.ToInt32(txt_width.Text);
                faceconfig["captureStandard"]["targetStandard"] = new JObject();
                faceconfig["captureStandard"]["targetStandard"]["fixedEnable"] = cb_fixedEnable.Text;
                faceconfig["captureStandard"]["targetStandard"]["fixedSize"] = Convert.ToInt32(txt_fixedSize.Text);
                faceconfig["captureStandard"]["targetStandard"]["imageType"] = txt_imageType.Text;
                faceconfig["captureStandard"]["targetStandard"]["upperHeightRatio"] = Convert.ToDouble(txt_underHeightRatio.Text);
                faceconfig["captureStandard"]["targetStandard"]["widthRatio"] = Convert.ToDouble(txt_widthRatio.Text);

                string response = httpClient.Post("/grg/camera/setFaceConfig", faceconfig.ToString());
                listBox1.Items.Insert(0, response);
            }
        }

        private void btn_get_roi_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                tb_rois.Rows.Clear();
                JObject body = new JObject();
                body["cameraId"] = Convert.ToInt32(txt_camId.Text);
                string response = httpClient.Post("/grg/camera/getMonitorRoi", body.ToString());
                listBox1.Items.Insert(0, response);

                JObject roiconfig = JObject.Parse(response);

                if (roiconfig["code"].ToObject<int>() == 0)
                {
                    cb_roi_enabled.Text = roiconfig["data"]["interestRegion"]["enabled"].ToObject<string>();
                    JArray rois = roiconfig["data"]["interestRegion"]["regionList"].ToObject<JArray>();
                    for (int i = 0; i < rois.Count; i++)
                    {
                        JObject roi = rois[i].ToObject<JObject>();
                        tb_rois.Rows.Add(new object[] {
                            roi["id"].ToObject<int>(),
                            roi["left"].ToObject<int>(),
                            roi["top"].ToObject<int>(),
                            roi["right"].ToObject<int>(),
                            roi["bottom"].ToObject<int>(),});
                    }
                }
            }
        }

        private void btn_set_roi_Click(object sender, EventArgs e)
        {
            if (httpClient != null && tb_rois.Rows.Count >= 2)
            {
                JObject roiconfig = new JObject();
                roiconfig["interestRegion"] = new JObject();
                roiconfig["interestRegion"]["enabled"] = cb_roi_enabled.Text;
                JArray regionList = new JArray();
                for (int i = 0; i < tb_rois.Rows.Count - 1; i++)
                {
                    JObject roi = new JObject();
                    roi["id"] = (int)tb_rois.Rows[i].Cells[0].Value;
                    roi["left"] = (int)tb_rois.Rows[i].Cells[1].Value;
                    roi["top"] = (int)tb_rois.Rows[i].Cells[2].Value;
                    roi["right"] = (int)tb_rois.Rows[i].Cells[3].Value;
                    roi["bottom"] = (int)tb_rois.Rows[i].Cells[4].Value;
                    regionList.Add(roi);
                }
                roiconfig["interestRegion"]["regionList"] = regionList;
                roiconfig["cameraId"] = Convert.ToInt32(txt_camId.Text);
                string response = httpClient.Post("/grg/camera/setMonitorRoi", roiconfig.ToString());
                listBox1.Items.Insert(0, response);
            }
        }
        Form2 textForm;
        private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (textForm == null || textForm.IsDisposed)
            {
                textForm = new Form2();
            }
            textForm.Show();
            textForm.showText(listBox1.SelectedItem.ToString());
        }

        private void btn_license_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject body = new JObject();
                body["code"] = txt_license_code.Text;
                string response = httpClient.Post("/grg/setAuthorize", body.ToString());
                listBox1.Items.Insert(0, response);
            }
        }

        private void btn_upload_Click(object sender, EventArgs e)
        {
            if (httpClient != null && openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txt_upload_filepath.Text = openFileDialog1.FileName;
                byte[] content = File.ReadAllBytes(openFileDialog1.FileName);
                IntPtr filedata = Marshal.AllocHGlobal(content.Length);
                Marshal.Copy(content, 0, filedata, content.Length);
                HttpWarpper.Post_Upload(httpClient.Ip, httpClient.Port, "/grg/debug", "image_file", filedata, content.Length, openFileDialog1.FileName.Split('\\').Last(), "multipart/form-data");
                Marshal.FreeHGlobal(filedata);
                //string response = httpClient.UploadRequest("/grg/debug", openFileDialog1.FileName);
                //listBox1.Items.Insert(0, response);


                //using (FileStream stream = File.OpenRead(openFileDialog1.FileName))
                //{
                //    byte[] content = new byte[stream.Length];

                //    for (int i = 0; i < content.Length; i++)
                //    {
                //        content[i] = (byte)stream.ReadByte();
                //    }

                //    string ctx = Encoding.Default.GetString(content);

                //    string response = httpClient.request("/grg/debug", ctx, HttpClient.RequestMethod.POST, "application/octet-stream");
                //    listBox1.Items.Insert(0, response);
                //}
            }
        }

        private void btn_capture_one_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject body = new JObject();
                body["devId"] = txt_devId.Text;
                string response = httpClient.Post("/grg/camera/captureOncePicture", body.ToString());
                int len = response.Length;
                listBox1.Items.Insert(0, response);
            }
        }

        private void btn_cap_info_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject body = new JObject();
                body["devId"] = txt_devId.Text;
                string response = httpClient.Post("/grg/camera/querySnapFace", body.ToString());
                int len = response.Length;
                listBox1.Items.Insert(0, response);
            }
        }

        private void btn_Clean_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
        }

        private void btnCleanFace_Click(object sender, EventArgs e)
        {
            tb_addperson_list.Rows.Clear();
        }

        private void btnWorkMode_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject body = new JObject();
                body["devId"] = txt_devId.Text;
                string response = httpClient.Post("/grg/camera/getWorkMode", body.ToString());
                int len = response.Length;
                listBox1.Items.Insert(0, response);
            }
        }

        private void btn_motor_up_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject body = new JObject();
                body["devId"] = txt_devId.Text;
                string response = httpClient.Post("/grg/camera/motor_up", body.ToString());
                listBox1.Items.Insert(0, "up　>>>　" + response);
            }
        }

        private void btn_motor_stop_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject body = new JObject();
                body["devId"] = txt_devId.Text;
                string response = httpClient.Post("/grg/camera/motor_stop", body.ToString());
                listBox1.Items.Insert(0, "stop　>>>　" + response);
            }
        }

        private void btn_motor_down_Click(object sender, EventArgs e)
        {
            if (httpClient != null)
            {
                JObject body = new JObject();
                body["devId"] = txt_devId.Text;
                string response = httpClient.Post("/grg/camera/motor_down", body.ToString());
                listBox1.Items.Insert(0, "down　>>>　" + response);
            }
        }
    }
}
